import { FlowGlobalInfo } from 'admin/schema/FlowGlobalSet';
import { getFlowGlobalSet, saveFlowGlobalSet } from 'admin/servers/servers';
import { Button, Col, Form, message, Row } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import React, { useCallback, useEffect, useState } from 'react';
import { GlobalNotUnderstood } from './components/GlobalNotUnderstood';
import { GlobalTimeout } from './components/GlobalTimeout';
import './style.scss';

/**
 * 全局设置
 * AI管理-机器人管理-版本管理-配置话术流程-全局设置
 */
const FlowGlobalSet: React.FC<{ versionId: number }> = ({ versionId }) => {
  const [form] = useForm();
  const [loading, setLoading] = useState(false);
  const [maxNotUnderstood, setMaxNotUnderstood] = useState<number>(0);
  const [maxTimeout, setMaxTimeout] = useState<number>(0);
  /**初始化表单 */
  const initFlowGlobalSet = useCallback(async () => {
    // 请求接口
    try {
      const { data } = await getFlowGlobalSet({ versionId });
      if (data) {
        const {
          globalNotUnderstood: { notUnderstoodScripts },
          globalTimeout: { timeoutScripts },
        } = data;
        const n = notUnderstoodScripts?.length || 0;
        const m = timeoutScripts?.length || 0;
        setMaxNotUnderstood(n + 1);
        setMaxTimeout(m + 1);
        // 重置表单数据
        form.setFieldsValue(data);
      } else {
        setMaxNotUnderstood(2);
        setMaxTimeout(2);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [versionId]);

  useEffect(() => {
    initFlowGlobalSet();
    return () => {
      // cleanup;
    };
  }, [initFlowGlobalSet]);
  /**保存 */
  const onFinish = async (values: any) => {
    setLoading(true);
    const params: FlowGlobalInfo = { versionId, ...values };
    const a = JSON.parse(JSON.stringify(values.globalTimeout));
    console.log('超时-before', a);
    // 添加时间默认值5
    values.globalTimeout.timeoutScripts.forEach((value: any) => {
      value.timeout = value.timeout || 5;
    });
    values.globalTimeout.timeoutHangupTimeout = values.globalTimeout.timeoutHangupTimeout || 5;
    const b = JSON.parse(JSON.stringify(values.globalTimeout));
    console.log('超时-after', b);
    console.log(params, '提交保存的数据');
    try {
      await saveFlowGlobalSet(params);
      message.success('保存成功');
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setLoading(false);
  };
  return (
    <div className="flow-global-wrap">
      <Form
        layout="vertical"
        form={form}
        initialValues={{
          globalNotUnderstood: {
            notUnderstoodHangupScript: '',
            notUnderstoodScripts: [''],
          },
          globalTimeout: {
            timeoutHangupTimeout: 5,
            timeoutHangupScript: '',
            timeoutScripts: [
              {
                timeout: 5,
                script: '',
              },
            ],
          },
        }}
        onFinish={onFinish}
      >
        <Row gutter={48}>
          <Col md={18} lg={9} offset={2}>
            {maxNotUnderstood > 0 && <GlobalNotUnderstood max={maxNotUnderstood} />}
          </Col>
          <Col md={18} lg={9} offset={2}>
            {maxTimeout > 0 && <GlobalTimeout max={maxTimeout} />}
          </Col>
        </Row>
        <div className="btn-box">
          <Button type="primary" htmlType="submit" loading={loading}>
            保存
          </Button>
        </div>
      </Form>
    </div>
  );
};

export default FlowGlobalSet;
